package com.etocrm.saas.lib.base.resource.exception;

import com.etocrm.saas.lib.base.common.result.Result;
import com.etocrm.saas.lib.base.common.result.ResultCodeEnum;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 权限异常处理
 */
@Slf4j
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        log.info("权限不足:" + accessDeniedException.getMessage());
        accessDeniedException.printStackTrace();
        if(accessDeniedException.getMessage().contains("不允许访问")){
            ObjectMapper objectMapper = new ObjectMapper();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            response.getWriter().write(objectMapper.writeValueAsString(Result.fail(ResultCodeEnum.USER_NO_PERMISSION_WARN)));
        }
    }

}
